package meijuli.com.join51.business.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.fragment.CommodityListFragment;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpCode;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Category;
import com.jhx.common.model.Event;
import com.jhx.common.model.EventBean;
import com.jhx.common.widget.CommonDialog;

import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.LogUtils;
import retrofit2.Call;

/**
 * 商品管理页面
 *
 * @author jack 2017-04-25 10:07
 */
public class CommodityManagementActivity extends BaseActivity {
    /**
     * 分类状态，1.上架0.下架
     */
    public final static int STATUS = 1;
    ViewPager mViewPager;
    FrameLayout mMenuFL;
    Toolbar mToolbar;
    TextView mMenuText;
    TextView mTextView;
    TabLayout mTabLayout;

    private PagerAdapter mPagerAdapter;
    private ArrayList<Category> mCategoryList;
    private List<Fragment> mFragmentList;
    private CommonDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_management);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
        initView();
        initToolbar();
        loadData();
    }

    private void initToolbar() {
        mTextView.setText("商品管理");
        mMenuText.setText("添加");
        mMenuText.setVisibility(View.VISIBLE);
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mMenuText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCategoryList == null) {
                    return;
                }
                Intent intent = new Intent(CommodityManagementActivity.this,
                        AddCommodityActivity.class);
                intent.putParcelableArrayListExtra(AddCommodityActivity.KEY_DATA, mCategoryList);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        mViewPager = findViewById(R.id.viewpager);
        mMenuFL = findViewById(R.id.fl_menu);
        mToolbar = findViewById(R.id.toolbar);
        mMenuText = findViewById(R.id.text_menu);
        mTextView = findViewById(R.id.toolbar_title);
        mTabLayout = findViewById(R.id.tablayout);
        mMenuFL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CommodityManagementActivity.this, CategoryActivity.class);
                intent.putParcelableArrayListExtra(AddCommodityActivity.KEY_DATA, mCategoryList);
                startActivityForResult(intent, 1001);
            }
        });
        mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    private void initData() {
        mCategoryList = new ArrayList<>();
        mFragmentList = new ArrayList<>();
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mCategoryList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            LogUtils.e(TAG, position + "<---->");
            return mCategoryList.get(position).getCategoryName();
        }
    }

    public void loadData() {
        showLoadingDialog();
        Map<String, String> map = new HashMap<>();
        map.put("status", Category.STATUS_OPEN + "");
        Call<HttpResponse<List<Category>>> call = ApiManager.get().getApiService(ApiService.class).getCategoryList(map);
        HttpRequest.getRequest().autoRecycle(this).start(call, false, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                mCategoryList.clear();
                mFragmentList.clear();
                mCategoryList = (ArrayList<Category>) data;
                boolean isHasOpenCategory = false;
                if (mCategoryList == null) {
                    showDialog();
                    return;
                }
                for (int i = 0; i < mCategoryList.size(); i++) {
                    if (mCategoryList.get(i).getStatus() == Category.STATUS_OPEN) {
                        isHasOpenCategory = true;
                        break;
                    }
                }
                if (!isHasOpenCategory) {
                    showDialog();
                    return;
                } else {
                    hideDialog();
                }
                for (int i = 0; i < mCategoryList.size(); i++) {
                    Category category = mCategoryList.get(i);
                    mFragmentList.add(CommodityListFragment.newInstance(category.getDmId(), i));
                }
                mPagerAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                if(errorCode == HttpCode.NOT_CATEGORY_CODE) {
                    showDialog();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (dialog != null) {
            dialog.dismiss();
        }
        dismissDialog();
    }

    @Subscribe
    public void onEvent(EventBean eventBean) {
        switch (eventBean.getStatus()) {
            case EventBean.STATUS_NEW_CATEGORY:
                loadData();
                break;
            default:

                break;
        }
    }

    @Subscribe
    public void onEvent(Event event) {
        if (event == null || event.getData() == null) {
            return;
        }
        int index = mCategoryList.indexOf(event.getData());
        if (index >= 0) {
            mTabLayout.getTabAt(index).select();
            mViewPager.setCurrentItem(index);
        }
    }

    public void showDialog() {
        dialog = new CommonDialog(CommodityManagementActivity.this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMessage("没有分类不允许添加商品额，去打开和添加分类");
        dialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onConfirmClick(View view) {
                Intent intent = new Intent(CommodityManagementActivity.this,
                        ClassificationActivity.class);
                startActivity(intent);
                dialog.dismiss();
            }

            @Override
            public void onCancelClick(View view) {
                finish();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    finish();
                }
                return false;
            }
        });
        dialog.show();
    }

    private void hideDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
